<!--
 * @Author       : tg
 * @LastEditors  : tg
 * @description  : 新增标签
 * @updateInfo   :
 * @Date         : 2023-10-20 14:39:40
 * @LastEditTime: 2023-10-20 15:35:09
-->
<script lang="ts" setup name="NewTwoTask">
import { organizaApi } from '@/MainApp/apis/organiza'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits<{
  (event: 'cancel'): void
  (event: 'update:visible', value: boolean): void
  (event: 'handConfirmChange', obj: any): void
  (event: 'confirm'): void
}>()

// const { lenName } = useLength()
// 表单
const formKey = {
  name: ''
}
const userFormRef = ref()
const userForm = ref(formKey)
const { msgSuccess, msgError } = useMessage()
const userRules = useFormRules([
  {
    key: 'name',
    required: true,
    trigger: 'blur',
    msg: '请输入标签名称'
  }
])
const { dialog } = useConfig()
// 加载
const loading = ref(false)
// 显示弹框
const dVisible = ref(props.visible)

watch(
  () => props.visible,
  bool => {
    dVisible.value = bool
  }
)
// 弹框打开
const handOpen = async () => {
  userFormRef.value?.resetFields()
}
// 取消
const handCancel = () => {
  emits('update:visible', false)
  emits('cancel')
  userFormRef.value?.resetFields()
}
// 关闭弹框
const handClosed = () => {
  handCancel()
}
// 保存
const handConfirm = async () => {
  userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const params = {
        ...userForm.value
      }
      const { success, msg, data } = await organizaApi.labelAdd(params)
      if (success) {
        msgSuccess(msg)
        // 新增成功返回时需要携带成功的任务id
        emits('handConfirmChange', data)
        handClosed()
      }
      else { msgError(msg) }
      loading.value = false
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    v-loading="loading"
    :rules="userRules"
    title="新增标签"
    :width="dialog.l"
    draggable
    align-center
    :close-on-click-modal="false"
    @closed="handClosed"
    @open="handOpen"
  >
    <el-form
      ref="userFormRef"
      :model="userForm"
      :rules="userRules"
      lab
      el-width="120px"
      label-width="80px"
    >
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="userForm.name"
          clearable
          :rows="3"
          type="textarea"
          maxlength="20"
          show-word-limit
          placeholder="请输入标签名称"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button bg text @click="handClosed">取消</el-button>
        <el-button
          v-loading="loading"
          bg
          type="primary"
          @click="handConfirm"
        >
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
